package utils

import (
	"container/list"
	beego "github.com/beego/beego/v2/adapter"
	"golang.org/x/net/websocket"
	"log"
	"net/http"
	"ocane/rpc"
	"strings"
)


type ReciveMsgDTO struct {
	Name string `json:"name"`
	Message string `json:"message"`
	ws *websocket.Conn
}


var (
	ReciveMsgChannel = make(chan ReciveMsgDTO, 10)
	subscribers = list.New()
	errorMsg = list.New()
	LoginKeyChannel = make(chan string,10)
)

//Persistence 持久化发送异常信息到redis,定时任务，每一秒钟持久化一次
func Persistence() {

}
//ResetToCh  服务启动，将redis中的部分数据数据刷新到内存中来
//如果用户连接及登陆后，则先从本地缓存中取数据，如果没有则去redis中取数据，这样保证消息不丢失
func ResetToCh()  {

}




func Echo(ws *websocket.Conn){
	for  {
	//	userNameRequest:= getUserName(ws.Request().RequestURI)
	//	if errorMsg.Len()>0{
	//		for front := errorMsg.Front();front!=nil;front= front.Next(){
	//			if front.Value.(ReciveMsgDTO).Name == userNameRequest{
	//				err := websocket.Message.Send(ws, userNameRequest+" 说："+front.Value.(ReciveMsgDTO).Message)
	//				if err==nil {
	//
	//					//errorMsg.Remove(front)
	//				}
	//			}
	//		}
	//	}
	//	dto := ReciveMsgDTO{ws: ws,Name: userNameRequest}
		dto := ReciveMsgDTO{"","",ws}
		subscribers.PushFront(dto)
		var msg string
		err := websocket.Message.Receive(ws, &msg)
		if nil != err {
			panic(err)
			return
		}
		//wss = ws
		log.Println("接收到websocket客户端消息：",msg)
		split := strings.Split(msg,":")
		/*currentUserId := split[0]
		toUserId := split[1]
		reviceMsg := split[2]
		SetString(toUserId,currentUserId+":"+reviceMsg)
		getString := GetString(currentUserId)
		if getString!=""{
			fmt.Println(getString)
			i := strings.Split(getString,":")
			senderr := websocket.Message.Send(ws, "接收到："+i[0]+" 的消息："+i[1])
			if senderr!=nil{
				panic(senderr)
			}
		}*/
		userName := split[0]
		reciveMsg := split[1]
		//PublishMessage("msg"+toUserId,msg)
		//Subscribe("msg"+currentUserId)
		ReciveMsgChannel<-ReciveMsgDTO{userName,reciveMsg,ws}
	}
}

func SendMsgInit()  {
	for  {
		select {
		case msg:=<-ReciveMsgChannel:
			for  sub := subscribers.Front(); sub != nil; sub = sub.Next() {
				err := websocket.Message.Send(sub.Value.(ReciveMsgDTO).ws, msg.Name+" 说 ："+msg.Message)
				if err!=nil{
					//ReciveMsgChannel<-msg
					dto := ReciveMsgDTO{Message: msg.Message, Name: sub.Value.(ReciveMsgDTO).Name}
					errorMsg.PushFront(dto)
				}
			}

		}
	}
}

func SendLoginKey(){
	for{
		select {
		case loginKey:=<-LoginKeyChannel:
			for sub := subscribers.Front(); sub != nil; sub = sub.Next() {
				err := websocket.Message.Send(sub.Value.(ReciveMsgDTO).ws, loginKey)
				if err!=nil{
					log.Println("登录回告失败：",loginKey,err)
					//panic(err)
				}
			}

		}
	}
}

func getUserName(url string) string {
	split := strings.Split(url, "?")
	if len(split)==0||split[1]==""{
		panic("登陆人为空 ")
	}
	s := split[1]
	i := strings.Split(s, "=")
	return i[1]
}

func init()  {

	http.Handle("/",websocket.Handler(Echo))
	log.Println("开始连接webSocket....")
	webSocketPort := beego.AppConfig.String("webSocketPort")
	go http.ListenAndServe(":"+webSocketPort, nil)
	log.Println("webSocket 服务端启动成功")
	go Subscribe("msg")
	go SendMsgInit()
	go SendLoginKey()
	go rpc.InitRpc()
	go rpc.InitRpcClient()
}

func SendMsg(msg string)  {
/*	if msg==""{
		return
	}
	split := strings.Split(msg,":")
	currentUserId := split[0]
	reviceMsg := split[2]

	senderr := websocket.Message.Send(wss, "接收到："+currentUserId+" 的消息："+reviceMsg)
	if senderr!=nil{
		panic(senderr)
	}*/
}

